(function () {
  //商品模板
  var sGoodsTemplate = '';
  var sRandomGoodsTemplate = '';
  var oGoods = document.getElementById("goods");
  var oGoodsCategory = document.getElementById("goods_category");
    var goodsNav = document.getElementById("goods_nav");
    var randomShow = document.getElementById("random-show");
  /**
   * 更新购物车
   * @param data, 包含商品编号和商品数量
   */
  var updateCart = function(data){
    $.post(
        ucshop.updataCartAddress(),
        data,
      function(err,data){
        try {
          var dataJson = JSON.parse(data);
          if (dataJson== ucshop.CODE.success) {
            alert('添加购物车成功');
          } else {
            alert('系统错误');
          }
        } catch(e) {
          console.log(e.errors);
        }
      }
    );
  };

  /**
   * 处理商品
   */

  var doGoods = function(d) {
      ucshop.clearRange();
      var discount= d[0].discount=='0'?1:(parseFloat(d[0].discount,1)/10);
      d[0].discountPrice=parseFloat(d[0].price*discount).toFixed(2);
    try {
      $.children(goodsNav,2).innerHTML="&gt;&nbsp;"+d[0].goodsName;
      var sDiv = $.compile(sGoodsTemplate, d[0]);
      oGoods.innerHTML = sDiv;
      /*数量操作*/
        var optBtn=document.querySelector(".optBtn");
        var goodsNumInput=document.querySelector(".buyNum");
        var goodsNum=goodsNumInput.value;
      $.addEvent(optBtn,"click",function (event) {
    event= event||window.event;
    switch (event.target.className){
        case "btnUp" :
            goodsNum++;
            goodsNum=goodsNum>100?100:goodsNum;
            goodsNumInput.value=goodsNum;
            break;
        case "btnDown" :
            goodsNum--;
            goodsNum=goodsNum <1?1:goodsNum;
            goodsNumInput.value=goodsNum;
            break;
        default:
            break;
    }

});
      var detailShow = document.getElementById("detailShow");
      var oulShow=detailShow.getElementsByTagName("ul")[0];
      var goodsBenUrl=JSON.parse(d[0].goodsBenUrl);
      console.log(goodsBenUrl);
      var imgArrss=JSON.parse(d[0].imgsUrl);
      var imgArr=imgArrss.concat(goodsBenUrl);
      console.log(imgArr);
      $.each(imgArr,function(item, index){
          oulShow.innerHTML += '<li><img src="images/default.jpg" alt="" width="700px" ></li>';
      });
        //图片预加载开始
        var imgs = oulShow.getElementsByTagName("img");
        $.each(imgArr, function (item, index) {
            (function (index) {
                $.preLoadImg(imgArr[index], function (data) {
                    console.log(index);
                    imgs[index].src = data.src;
                });
            })(index);
        });
        //图片预加载结束
      var oCartBtn = oGoods.getElementsByClassName('addToCart')[0];
      oCartBtn.addEventListener('click', function(){
          var num=goodsNumInput.value;
        ucshop.checkLogin(function(){
            updateCart({goodsID: oCartBtn.getAttribute('data-goodsid'), number:num,userID:localStorage.getItem("userID")});
        }, function(){
          //未登录
          alert('未登录');
          window.open('login.html', '_top', 'height:300;width:500;scrollbars=no,location=no');
        });
      });
    } catch (e) {
      console.error('err');
      console.log(e.errors);
    }
  };
    /*处理随机商品*/
    var doRandomGoods = function(d) {
        d=$.sample(d,4);
        try {
            $.each(d, function (item) {
                var discount= item.discount=='0'?1:(parseFloat(item.discount).toFixed(1)/10);
                item.discountPrice=parseFloat(item.price*discount).toFixed(2);
                var sLi = $.compile(sRandomGoodsTemplate, item);
                randomShow.innerHTML += sLi;
            });
        } catch (e) {
            console.error(e);
        }
    };
  /**
   * 获取商品
   */
  var getGoods = function(){
    var goods_id = $.getQueryString("goodsID");
    $.loadTemplate('./template/detail_goods_info.html', function(err, data){
      if (err) {
        console.log(err);
        return;
      }
      sGoodsTemplate = data;

        $.jsonp(ucshop.getGoodsAddress(),{"goodsID": goods_id, "format": "jsonp", "callback": "doGoods"}, 'doGoods', doGoods);
    });
  };

  /**
   * 处理商品分类数据
   */
  var doGoodsCategory = function(){
      var classID = $.getQueryString("classID");
      var searchText=$.getQueryString("searchText");
      var goods=JSON.parse(window.sessionStorage.goods);
      var catName=goods[classID];
      var navResult=catName || "收索结果为："+searchText;
      $.children(goodsNav,1).innerHTML="<a href='javascript:javascript:history.go(-1);'>"+navResult+"</a>";
      var oGoodsCategoryTempt="";
      $.map(goods, function(key){
          oGoodsCategoryTempt +="<li><a href='list.html?classID="+key+"'><img src='./images/"+key+".png' width='50px'><p>"+goods[key]+"</p></a></li>"
      });
      oGoodsCategory.innerHTML=oGoodsCategoryTempt;
  };

  /*
   * 获取随机商品信息
   */
    var getRandomGoods = function(){
        var class_id = $.random(0,6);
        $.loadTemplate('./template/list_goods.html', function(err, data){
            if (err) {
                console.log(err);
                return;
            }
            sRandomGoodsTemplate = data;

            $.jsonp(ucshop.getGoodsAddress(),{"classID": class_id, "format": "jsonp", "callback": "doRandomGoods"}, 'doRandomGoods', doRandomGoods);
        });
    };

  window.onload = function() {
    ucshop.checkLoginStatus();
    ucshop.toTop();
    ucshop.slide_up();
    ucshop.searchGoods();
    ucshop.progress();
    //获取商品分类信息
    doGoodsCategory();
    //获取商品
    getGoods();
      //获取随机商品
      getRandomGoods();
  }
})();